let { list } = require('./mock')
const JWT = require('jsonwebtoken')
const userList = [{
	tel: '13111111111',
	email: "123456@qq.com",
	password: 'Q123456',
	nickname: "八维-阿三",
	avator: 'https://robohash.org/123',
	role: 'admin'
}, {
	tel: '13222222222',
	email: "123456@163.com",
	password: 'W123456',
	nickname: "有梦想的程序员",
	avator: 'https://robohash.org/123123?set=set3',
	role: 'user'
}, {
	tel: '13333333333',
	email: "123456@qq.cn",
	password: 'E123456',
	nickname: "是一个混子",
	avator: 'https://robohash.org/98765?set=set4',
	role: 'test'
}]
const bodyParser = require('body-parser')
module.exports = app => {
	app.use(bodyParser.json());

	app.post('/api/login', (req, res) => {
		// 1. 获取用户名和密码
		const { username, password } = req.body;
		// 2. 匹配
		const user = userList.find(v => {
			return (v.tel === username && v.password === password) || ((v.email === username && v.password === password))
		})
		// 3.判断
		if (user) {
			res.send({
				code: 200,
				data: {
					nickname: user.nickname,
					tel: user.tel,
					email: user.email,
					avator: user.avator,
					role: user.role,
					token: JWT.sign({
						nickname: user.nickname,
						tel: user.tel,
						email: user.email,
						avator: user.avator,
						role: user.role,
					}, '123456')
				},
				message: '登录成功， 欢迎' + user.nickname
			})
		} else {
			res.send({
				code: 400,
				message: '账户密码错误， 请重新登录'
			})
		}
	})

	app.get('/api/list', (req, res) => {
		const { wd, type  } = req.query;
		let copyList = [...list];

		// 1. 是否模糊搜索 
		if(wd) {
			copyList = copyList.filter(v => {
				return JSON.stringify(v).includes(wd)
			})
		}

		// 2. 是否类型查找
		if(type && type !== '全部') {
			copyList = copyList.filter(v => v.type === type)
		}
		res.send({
			code: 200,
			data: copyList,
			message: '数据请求成功~'
		})
	})

	app.delete('/api/list', (req, res) => {
		const { id } = req.query;
		list = list.filter(v => {
			return !id.includes(v.id)
		});
		res.send({
			code: 200,
			message: '数据删除成功',
			data: list
		})
	})

	app.post('/api/list', (req, res) => {
		const { id } = req.body;
		const item = list.find(v => v.id === id);
		Object.assign(item, req.body);
		res.send({
			code: 200,
			data: list,
			message: '数据修改成功！！'
		})
	})

	app.put('/api/list', (req, res) => {
		list.unshift(req.body)
		res.send({
			code: 200,
			data: list,
			message: '数据添加成功！！'
		})
	})
}